package hu.dobrosi.j2me.io;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;
import javax.microedition.lcdui.Image;

public class ImageReader {

	public static Image getImage(String url) throws IOException {
		ContentConnection connection = (ContentConnection) Connector.open(url);

		// * There is a bug in MIDP 1.0.3 in which read() sometimes returns
		// an invalid length. To work around this, I have changed the
		// stream to DataInputStream and called readFully() instead of read()
		// InputStream iStrm = connection.openInputStream();
		DataInputStream iStrm = connection.openDataInputStream();

		ByteArrayOutputStream bStrm = null;
		Image im = null;

		try {
			// ContentConnection includes a length method
			byte imageData[];
			int length = (int) connection.getLength();
			if (length != -1) {
				imageData = new byte[length];

				// Read the png into an array
				// iStrm.read(imageData);
				iStrm.readFully(imageData);
			} else // Length not available...
			{
				bStrm = new ByteArrayOutputStream();

				int ch;
				while ((ch = iStrm.read()) != -1)
					bStrm.write(ch);

				imageData = bStrm.toByteArray();
				bStrm.close();
			}

			// Create the image from the byte array
			im = Image.createImage(imageData, 0, imageData.length);
		} finally {
			// Clean up
			if (iStrm != null)
				iStrm.close();
			if (connection != null)
				connection.close();
			if (bStrm != null)
				bStrm.close();
		}
		return (im == null ? null : im);
	}
}